from flask import current_app,redirect
from flask import g,session,url_for
from flask import request,render_template, jsonify
from info import constants, db
from info.models import User, News,Category
from info.utlis.response_code import RET
from . import admin_bp
from info.utlis.common import login_user_data
from datetime import datetime
from datetime import timedelta
import time
from info.utlis.image_store import qiniu_image_store


# 要审核新闻展示
@admin_bp.route('/news_review')
@login_user_data
def new_review():
    p = request.args.get("p",1)
    keywords = request.args.get("keywords")
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    items = []
    current_page = 1
    total_page = 1
    filter = [News.status != 0]
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc())\
            .paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for item in items if items else []:
        news_dict_list.append(item.to_review_dict())

    data = {
        "news_list":news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }

    return render_template("admin/news_review.html",data=data)

# 要编辑新闻展示
@admin_bp.route('/news_edit')
@login_user_data
def news_edit():
    # 一页展示多少条数据
    p = request.args.get("p", 1)
    keywords = request.args.get("keywords")
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    news_list = []
    current_page = 1
    total_page = 1
    filter = []
    if keywords:
        filter.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filter).paginate(p, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        items = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    news_dict_list = []
    for item in items if items else []:
        news_dict_list.append(item.to_review_dict())
    data = {
        "news_list": news_dict_list,
        "current_page": current_page,
        "total_page": total_page
    }

    return render_template("admin/news_edit.html", data=data)

# 编辑新闻
@admin_bp.route("/news_edit_detail",methods=['post','get'])
@login_user_data
def news_edit_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        news_dict = news.to_dict() if news else None
        try:
            cateories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        cateories.pop(0)
        category_dict_list = []
        for category in cateories if cateories else []:
            category_dict = category.to_dict()
            category_dict["is_selected"] = False
            if category.id == news.category_id:
                category_dict["is_selected"] = True
            category_dict_list.append(category_dict)
        data = {
            "news":news_dict,
            "categories":category_dict_list
        }
        return render_template("admin/news_edit_detail.html",data=data)

    # POST请求修改新闻内容
    # 1.获取参数
    news_id= request.form.get("news_id")
    title= request.form.get("title")
    digest= request.form.get("digest")
    content= request.form.get("content")
    index_image= request.files.get("index_image")
    category_id= request.form.get("category_id")

    if not all([news_id,title,digest,content,category_id]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻对象异常")
    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻为空")

    if index_image:
        index_image_data = index_image.real()

        try:
            image_name = qiniu_image_store(index_image_data)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR,errmsg="第三方异常")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name

    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="提交新闻修改内容异常")

    return jsonify(errno=RET.OK,errmsg="新闻编辑成功")

# 新闻分类展示
@admin_bp.route("/category_type")
def category_type():
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    categories.pop(0)
    category_dict_list = []
    for category in categories if categories else []:
        category_dict_list.append(category.to_dict())

    data = {
        "categories":category_dict_list
    }
    return render_template("admin/news_type.html",data=data)

# 添加分类
@admin_bp.route("/add_category",methods=["post"])
def add_category():
    category_id = request.json.get("id")
    category_name = request.json.get("name")

    if not category_name:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    #
    if category_id:
        category = None
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询新闻分类异常")
        if not category:
            return jsonify(errno=RET.NODATA,errmsg="分类不存在")
        category.name = category_name
    else:
        category1 = Category()
        category1.name = category_name
        db.session.add(category1)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存分类对象异常")

    return jsonify(errno=RET.OK, errmsg="OK")


# 审核新闻提交页面
@admin_bp.route('/news_review_detail',methods=['get','post'])
@login_user_data
def news_review_detail():
    if request.method == "GET":
        news_id = request.args.get("news_id")
        try:
            if news_id:
                news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        news_dict = news.to_dict() if news else None
        data = {
            "news":news_dict
        }
        return render_template("admin/news_review_detail.html",data=data)

    news_id = request.json.get("news_id")
    action = request.json.get("action")

    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不足")
    if action not in ["accept","reject"]:
        return jsonify(errno=RET.PARAMERR,errmsg="action参数有误")

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询新闻对象异常")

    if not news:
        return jsonify(errno=RET.NODATA,errmsg="新闻为空")
    if action == "accept":
        news.status = 0
    else:
        reason = request.json.get("reason")
        if reason:
            news.reason = reason
            news.status = -1
        else:
            return jsonify(errno=RET.PARAMERR,errmsg="未填写拒绝原因")
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="保存新闻状态异常")

    return jsonify(errno=RET.OK,errmsg="OK")

# 用户列表
@admin_bp.route('/user_list')
@login_user_data
def user_list():
    # 一页展示多少条数据
    p = request.args.get("p",1)
    user = g.user
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    news_list = []
    current_page = 1
    total_page = 1
    if user:
        try:
            paginate = User.query.paginate(p,constants.ADMIN_USER_PAGE_MAX_COUNT,False)
            items = paginate.items
            current_page = paginate.page
            total_page = paginate.pages
        except Exception as e:
            current_app.logger.error(e)
    user_dict_list = []
    for item in items if items else []:
        user_dict_list.append(item.to_dict())
    data = {
        "users":user_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }

    return render_template("admin/user_list.html",data=data)

# 展示用户数据
@admin_bp.route('/user_count')
@login_user_data
def user_count():
    """展示用户统计页面"""
    # 查询总人数
    total_count = 0
    try:
        # 10001
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询月新增数
    mon_count = 0
    try:
        # 2018-8-31号
        now = time.localtime()
        # 2018-08-01月初  2018-09-01
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # 使用strptime将字符串转成时间date格式 '%Y-%m-%d'
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        # 用户的创建时间 > 每一个月的第一天 -->每一个月的新增人数
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询日新增数
    day_count = 0
    try:
        # 2018-08-31-0:0
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        # 当前时间 > 2018-08-31-0:0(一天的开始时间)
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查询图表信息
    # 获取到当天00:00:00时间
    # 2018-08-31
    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定义空数组，保存数据
    active_date = []
    active_count = []

    # 依次添加数据，再反转
    for i in range(0, 31):
        # 2018-08-31 - 1  =  2018-08-30:0:0
        # 2018-08-31 - 2  =  2018-08-29:0:0
        begin_date = now_date - timedelta(days=i)
        #  now_date - timedelta(days=(i))  + timedelta(days=(1))
        #  begin_date + timedelta(days=(1))
        # 2018-08-30:24:00
        # 2018-08-29:24:00
        end_date = begin_date + timedelta(days=1)
        # 记录这个月的每一天  30 29 ....01
        # strftime将date格式转换成字符串
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        # 记录一个月的每天的用户活跃数
        active_count.append(count)

    # 日期反转
    active_date.reverse()
    # 数据反转
    active_count.reverse()

    data = {"total_count": total_count, "mon_count": mon_count, "day_count": day_count, "active_date": active_date,
            "active_count": active_count}


    return render_template('admin/user_count.html',data=data)


# 不管用户登未登录想请求/admin/index页面前勾子函数会拦截，请求/admin/login能正常请求
# 当管理员登录后想请求/admin/index能正常请求，请求/admin/login会自动跳转到/admin/index
# 用户退出登录后要清除掉session中的is_admin值
@admin_bp.route('/index')
@login_user_data
# 管理员界面
def admin_index():
    user = g.user
    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("admin/index.html",data=data)


# 登录界面
@admin_bp.route('/login',methods = ['post','get'])
@login_user_data
def admin_login():
    if request.method == 'GET':
        user_id = session.get('user_id',None)
        is_admin = session.get('is_admin',None)
        # 用户登录过并且是管理员身份登录才自动登录
        if user_id and is_admin:
            return redirect(url_for("admin_bp.admin_index"))

        return render_template("admin/login.html")

    # post请求获取用户提交数据进行登录校验
    # 1.获取参数
    username = request.form.get("username")
    password = request.form.get("password")

    if not all([username,password]):
        return render_template("admin/login.html",errmsg="参数不足")
    user = None # type:User
    try:
        user = User.query.filter(User.mobile==username,User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="查询管理员失败")
    if not user:
        return render_template("admin/login.html",errmsg="没有该用户名")

    if not user.check_passowrd(password):
        return render_template("admin/login.html",errmsg="密码填写错误")
    # 登录成功后保存session值下次自动登录
    session["mobile"] = username
    session["is_admin"] = True
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name

    return redirect(url_for("admin_bp.admin_index"))